package com.sam.im.heiqun.app;

import android.content.Context;
import android.content.Intent;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;
import android.util.Log;

import com.iflytek.cloud.SpeechUtility;
import com.melink.bqmmsdk.sdk.BQMM;
import com.netease.nis.bugrpt.CrashHandler;
import com.orm.SugarContext;
import com.sam.im.heiqun.callmain.RtcSdpObserver;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.nets.PGApi;
import com.sam.im.heiqun.service.AcceptService;
import com.sam.im.heiqun.sound.ChatCallActivity;
import com.sam.im.heiqun.sound.entity.EngineConfig;
import com.sam.im.heiqun.sound.receiver.WorkerThread;
import com.sam.im.heiqun.utils.EventBusTypeData;
import com.sam.im.heiqun.utils.ServiceDataAnalyse;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.shuyu.gsyvideoplayer.cache.ProxyCacheManager;
import com.yuyh.library.AppUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;
import org.webrtc.IceCandidate;
import org.webrtc.PeerConnection;
import org.webrtc.PeerConnectionFactory;

import java.net.URISyntaxException;

import io.socket.client.Ack;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;

/**
 * Created by Joe on 2016/12/31.
 */

//public class App extends SugarApp {
    /*方法超限第三步*/
public class App extends MultiDexApplication {
    private static App mApp;
    public static Socket socket = null;
    public static boolean isManualLogout = false;

    //    public static String loginUrl = "http://192.168.1.101/wms/";
//    public static String loginUrl = "http://oa.hewenjun.cn/wmsMobile/";
    public static String loginUrl = PGApi.getPayPalUrl;
    //    public static String imageUrl = "http://oa.hewenjun.cn/wmsMobile/";
    public static String imageUrl = PGApi.getPayPalUrl;

    public static String imIpAfterReady = "";

    public static String tokenAfterReady = "";
    public static String phone = "";

    public static int NET_STATE = 1;//1:有网络 2：没有网络

    public static UserEntivity userEntivity;
    public static long destid = -1;//当前聊天的id
    public static String rtcdestid = "";
    public static int messageType = Constant.FROM_TYPE_MAM;//1：单人 2：群
    public static boolean iscallvideoing = false;//正在视屏聊天中

    public synchronized static App getInstance() {
        return mApp;
    }

    /**
     * 视屏通话
     */
    public static RtcSdpObserver observer = new RtcSdpObserver();
    public static PeerConnectionFactory pcFactory = null;
    public static PeerConnection pc = null;
    WorkerThread mWorkerThread;

    private static int numConnect = 0 ;

    @Override
    public void onCreate() {
        super.onCreate();
        SugarContext.init(this);
        AppUtils.init(this);
        // LeakCanary.install(this);//内存泄漏检测
        //表情云
        BQMM.getInstance().initConfig(getApplicationContext(), "5779d4d4fbd940ab9123f1b503fb1b35", "e674a462760d48cd8e13dbf402576a8c");
        mApp = this;
//        Bugly.init(getApplicationContext(), "1a35c6b826", false);
        CrashHandler.init(getApplicationContext());

        // 讯飞 注意： appid 必须和下载的SDK保持一致，否则会出现10407错误
        SpeechUtility.createUtility(App.this, "appid=59b099a4");

        ToolsUtils.context = this;

      /* bus = new Bus(ThreadEnforcer.ANY);
        aio = new AudioIO(this, bus, 8000, false);*/
        //resetDefaultServer();
        // initSmallVideo(getApplicationContext());
        //CrashReport.initCrashReport(getApplicationContext(), "1a35c6b826", false);
        EngineConfig mEngineConfig = new EngineConfig();
        if (mWorkerThread == null) {
            mWorkerThread = new WorkerThread(getApplicationContext());
            mWorkerThread.start();

            mWorkerThread.waitForReady();
        }


    }

    @Override
    public void onTerminate() {
        SugarContext.terminate();
        super.onTerminate();
    }

    public Socket getSocket() {
        return socket;
    }

    public void startAcceptService() {
        Intent intent = new Intent(this, AcceptService.class);
        startService(intent);
    }

    public static void createSocket(String token) throws Exception{
        IO.Options opts = new IO.Options();
        opts.forceNew = false;
        opts.reconnection = true;
        if (socket != null) {
            socket.close();
            socket = null;
        }
        //http://wslm.hui2013.com:9092
        socket = IO.socket("http://" + PGApi.getFWUrl + ":9092?token=" + token + "&device=1", opts);
    }

    public static void initSocket(String address, String token) {
        try {
            createSocket(token);
//            socket = IO.socket("http://" + address + ":9092?token=" + token + "&device=1", opts);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null == socket){
            if (numConnect < 9){
                numConnect++;
                initSocket(address, token);
            }
            return;
        }
        socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                numConnect = 0 ;
                EventBus.getDefault().post(Constant.FRAGMENT_HIND_TITLE);
            }
        }).on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {
            @Override
            public void call(Object... objects) {
                if (numConnect < 9){
                    numConnect++;
                    socket.connect();
                }
            }
        }).on(Socket.EVENT_CONNECT_TIMEOUT, new Emitter.Listener() {
            @Override
            public void call(Object... objects) {
                if (numConnect < 9){
                    numConnect++;
                    socket.connect();
                }
            }
        })
                .on("echo", new Emitter.Listener() {
            @Override
            public void call(Object... objects) {
                Ack ack = (Ack) objects[objects.length - 1];// 最后一个参数为服务器的ack
                ack.call();
            }
        })
                .on("chat", new Emitter.Listener() {
                    //聊天事件
                    @Override
                    public void call(final Object... args) {
                        Ack ack = (Ack) args[args.length - 1];//最后一个参数为服务器的ack
                        ack.call();
                        String msg = String.valueOf(args[0]);
                        try {
                            final JSONObject js = new JSONObject(msg);
                            //处理offer
                            int msgType = js.getInt("messageType");

                            long nowTime = System.currentTimeMillis();
                            long sendTime = js.getLong("sendTime");
                            boolean flag=false;
                            if ((nowTime-Long.parseLong(sendTime+""))<10*1000){
                                flag=true;
                            }
                            Log.i("fanhui","js:"+js);
                            if (flag&&msgType>=150){
                                if (msgType == 150 || msgType == 151) {
                                    //请求音频通话
                                    EventBus.getDefault().post(new EventBusTypeData(Constant.TOMessageTypeVoiceRequest, msg));

                                } else if (msgType == 152 || msgType == 153) {
                                    //同意音频通话
                                    EventBus.getDefault().post(new EventBusTypeData(Constant.TOMessageTypeAgreeVoiceRequest, msg));

                                } else if (msgType == 155 || msgType == 154) {
                                    //拒绝音频通话
                                    EventBus.getDefault().post(Constant.TOMessageTypeRefuseVideoRequest);
                                    EventBus.getDefault().post(new EventBusTypeData(Constant.SWICHVICEOSHOWVIDEONOTIMREFUSE, ToolsUtils.getMyUserId()));
                                } else if (msgType == 157) {
                                    //视频切换音频
                                    EventBus.getDefault().post(Constant.TOMessageTypeChangeVideoToVoiceRequest);
                                } else if (msgType == 158) {
                                    //音频切换视频
                                    EventBus.getDefault().post(new EventBusTypeData(Constant.VICEOSHOWVIDEO, msg));
                                } else if (msgType == 159) {
                                    //对方同意音频切换视频
                                    EventBus.getDefault().post(Constant.SWICHVICEOSHOWVIDEO);
                                } else if (msgType == 156) {
                                    //挂断对方音视频

                                    EventBus.getDefault().post(new EventBusTypeData(Constant.TOVIDEOTHREECALLEXIT, msg));


                                } else if (msgType == 160) {
                                    //对方拒绝音频切换视频
                                    EventBus.getDefault().post(Constant.SWICHVICEOSHOWVIDEONO);
                                } else if (msgType == Constant.TOMessageTypeRefuseChangeVoiceTRYToVideoRequest) {
                                    //异常退出
                                    EventBus.getDefault().post(Constant.SWICHVICEOSHOWVIDEONOTIMREFUSEEXXIT);

                                }
                            }else{
                                if (msgType == 49) {
                                    JSONObject contentjs = new JSONObject(js.getString("content"));
                                    Log.i("info", "=======app49");
                                    IceCandidate candidate = new IceCandidate(
                                            contentjs.getString("sdpMid"),
                                            contentjs.getInt("sdpMLineIndex"),
                                            contentjs.getString("candidate")
                                    );
                                    pc.addIceCandidate(candidate);
                                } else if (msgType == 47 || msgType == 48) {
                                    /**
                                     * 这里47和48用在群公告的创建和编辑了
                                     * 不知怎么搞的
                                     */

//                        JSONObject contentjs=new JSONObject(js.getString("content"));
//                        Log.i("info", "call: ==="+js.toString());
//                        SessionDescription sdp = new SessionDescription(
//                                SessionDescription.Type.fromCanonicalForm(contentjs.getString("type")),
//                                contentjs.getString("sdp"));
//                        pc.setRemoteDescription(observer,sdp);
//                        Log.i("info","=======app48");
//                        if(msgType==47){
//                            pc.createAnswer(observer, RtcUtil.getPcConstraints());
//                            //发送answer消息
//                            JSONObject payload = new JSONObject();
//                            payload.put("type", sdp.type.canonicalForm());
//                            payload.put("sdp", sdp.description);
//                            String sendSdp= payload.toString();
//                            Log.i("info","=======app47");
//                            socket.emit("chat", IMMessage.createSimpleMsg(sendSdp, 48), new Ack() {
//                                @Override
//                                public void call(Object... args) {
//                                    System.out.println("answer sent...");
//                                }
//                            });
//                        }
                                }

                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        ServiceDataAnalyse.onMessage(args);
                                    }
                                }).start();
                            }





					/*
                    if(context!=null){
						context.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								try {
									Toast.makeText(getApplicationContext(), js.getString("content"), Toast.LENGTH_SHORT).show();
								} catch (JSONException e) {
									e.printStackTrace();
								}
							}
						});
					}
					*/

                        } catch (Exception e) {
                            e.printStackTrace();
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    ServiceDataAnalyse.onMessage(args);
                                }
                            }).start();
                        }

                    }
                })
                .on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {

                    @Override
                    public void call(Object... args) {
                        if (null != socket) {
                            Log.e("info", "进入这里EVENT_DISCONNECT");
                            //socket.close();
                            // socket = null;
                        }
                    }

                });
        socket.connect();
    }
    //初始化小视屏录制
  /*  public static void initSmallVideo(Context context) {
        // 设置拍摄视频缓存路径
        File dcim = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        if (DeviceUtils.isZte()) {
            if (dcim.exists()) {
                VCamera.setVideoCachePath(dcim + "/easyimVideo/");
            } else {
                VCamera.setVideoCachePath(dcim.getPath().replace("/sdcard/",
                        "/sdcard-ext/")
                        + "/easyimVideo/");
            }
        } else {
            VCamera.setVideoCachePath(dcim + "/easyimVideo/");
        }
        VCamera.setDebugMode(true);
        VCamera.initialize(context);
    }*/

    /**
     * 方法超限第四步
     * <p>
     * 分割 Dex 支持
     *
     * @param base
     */
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public synchronized WorkerThread getWorkerThread() {
        return mWorkerThread;
    }

}
